package net.java.aioechotest;

import net.java.nioserver.utils.ChannelUtil;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;

import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

/**
 * @author Leonid Shlyapnikov
 */
public class OpAcceptTask implements Runnable {

    private final static Logger log = LoggerFactory.getLogger(OpAcceptTask.class);

    private final SocketChannel sc;
    private Selector selector;

    public OpAcceptTask(SocketChannel sc, Selector selector) {
        this.sc = sc;
        this.selector = selector;
    }

    public void run() {

        if (null == sc) {
            log.warn("SocketChannel is null");
            return;
        }

        try {
            sc.configureBlocking(false);
            sc.register(selector, SelectionKey.OP_READ);

            if (log.isInfoEnabled()) {
                log.info("New connection: " + sc);
            }
        } catch (Exception e) {
            log.error("Cannot finish task: " + sc, e);
            ChannelUtil.close(sc);
        }
    }
}
